'use strict'
const { ContentError } = require('../lib/error')
const whiteList = require('../lib/whiteList')
const cheerio = require('cheerio');
const articleServices = require('../services').articleService
const tagServices = require('../services').tagService

const localTime = require('../lib/localTime')

const articleController = {}

// 操作文章时处理TAG START
function queryTag (article) {
    if (!article.tagAdd) {
        article.tagAdd = []
    }
    if (!article.tagRemove) {
        article.tagRemove = []
    }

    let tags = article.tagAdd.concat(article.tagRemove)
    let query = tags.map(tag => {
        return { name: tag }
    })
    if (query.length === 0) {
        return []
    }
    return tagServices.getTag({ $or: query })
}

async function updateTag (article, dbTag = []) {
    await dealWithTagAdd(article.tagAdd, dbTag)
    await dealWithTagRemove(article.tagRemove, dbTag)
}

async function dealWithTagAdd (tags = [], dbTag) {
    let tagWillAdd = []
    let tagWillUpdate = []
    tags.map(tag => {
        let repeat =
            dbTag.some(db => {
                if (db.name === tag) {
                    db.count += 1
                    tagWillUpdate.push(db)
                    return true
                }
            })
        !repeat && tagWillAdd.push({ name: tag, count: 1 })
    })
    if (tagWillAdd.length > 0) {
        await tagServices.createTags(tagWillAdd)
    }
    if (tagWillUpdate.length > 0) {
        tagWillUpdate.map(async (tag) => {
            await tagServices.updateOneTag(tag._id, tag)
        })
    }
    return true
}

async function dealWithTagRemove (tags = [], dbTag) {
    let tagWillRemove = []
    let tagWillUpdate = []
    tags.map(tag => {
        let repeat =
            dbTag.some(db => {
                if (db.name === tag) {
                    if (db.count > 1) {
                        db.count -= 1
                        tagWillUpdate.push(db)
                    } else {
                        tagWillRemove.push(db)
                    }
                    return true
                }
            })
    })
    if (tagWillRemove.length > 0) {
        await tagServices.deleteTags({ _id: { $in: tagWillRemove } })
    }
    if (tagWillUpdate.length > 0) {
        tagWillUpdate.map(async (tag) => {
            await tagServices.updateOneTag(tag._id, tag)
        })
    }
    return true
}

// 操作文章时处理TAG END

articleController.getArticleCount = async (ctx, next) => {
    ctx.result = await articleServices.getArticleCount({ ...ctx.request.query })
    return next()
}
// 获取文章 分页 参数 需要考虑文章权限
articleController.getArticle = async (ctx, next) => {
    // whiteList.needAdmin(ctx, next)
    ctx.result = await articleServices.getArticle({ ...ctx.request.query })
    return next()
}

// 创建文章
articleController.createArticle = async (ctx, next) => {
    whiteList.needAdmin(ctx, next)
    const articleList = ctx.request.body
    // 文章标题长度校验
    let overLength = articleList.some(article => {
        return article.title.length > 50
    })
    if (overLength) {
        throw new ContentError('标题过长')
    }
    let createTime = localTime()
    let updateTime = localTime()

    articleList.map(async (article) => {
        const $ = cheerio.load(article.content)
        article.description = $.text().slice(0, 80) + '...'
        article.createTime = createTime
        article.updateTime = updateTime

        // 更新tag信息 没有事务 创建 标签全部加一
        // 1.查询标签
        let dbTags = await queryTag(article)
        console.log('dbTags', dbTags)
        // 2.进行比较 得出更新和新建的标签
        // 3.新建标签
        // 4.更新标签
        await updateTag(article, dbTags)

    })
    ctx.result = await articleServices.createArticle(articleList)


    return next()
}

// 删除文章
articleController.deleteArticle = async (ctx, next) => {
    whiteList.needAdmin(ctx, next)
    const articleList = ctx.request.body
    articleList.map(async (article) => {
        // 更新tag信息 没有事务 创建 标签全部减一
        // 1.查询标签
        let dbTags = await queryTag(article)
        // 2.数量为一 删除标签
        // 3.反之减一
        await updateTag(article, dbTags)
    })

    ctx.result = await articleServices.deleteArticle(articleList)
    return next()
}

// 编辑一个文章
articleController.updateOneArticle = async (ctx, next) => {
    // 不知道为啥updateArticleLikes会触发这个
    if (ctx.result) {
        console.log('updateOneArticle');
        return next()
    }
    whiteList.needAdmin(ctx, next)
    const article = ctx.request.body
    // 包含content 需要处理preview
    if (article.content) {
        const $ = cheerio.load(article.content)
        article.description = $.text().slice(0, 80) + '...'
        article.updateTime = localTime()
    }
    ctx.result = await articleServices.updateOneArticle(article._id, article)
    // 更新tag数量
    if (article.tagAdd || article.tagRemove) {
        // 1.查询标签
        let dbTags = await queryTag(article)
        // 2.进行比较 得出 更新|新建|删除 的标签
        await updateTag(article, dbTags)
    }
    return next()
}

articleController.updateArticleLikes = async (ctx, next) => {
    console.log('updateArticleLikes')
    const article = ctx.request.body
    ctx.result = await articleServices.updateArticle({ _id: article._id }, article)
    return next()
}

articleController.updateArticleComment = async (ctx, next) =>{
    // TODO 需要判断当前文章是否可以评论
    const comment = ctx.request.body
    ctx.result = await articleServices.updateArticleComment(comment)
    return next()
}

articleController.getHotArticle = async (ctx, next) => {
    ctx.result = await articleServices.getHotArticle(ctx.request.query.limit)
    return next()
}

// 获取置顶文章
articleController.getTopArticle = async (ctx, next) => {
    ctx.result = await articleServices.getTopArticle()
    return next()
}

// 获取每个分类下文章的总数
articleController.getArticleCountUnderCategory = async (ctx, next) => {
    ctx.result = await articleServices.getArticleCountUnderCategory()
    return next()
}


module.exports = articleController
